/**
 * 
 */
package com.hexacta.hrs.repositories.impl;

import java.util.Collection;

import org.hibernate.Query;
import org.vectrics.cv.PersonSkill;
import org.vectrics.recruiter.user.CandidateInfo;

/**
 * @author iandronowicz
 * 
 */
public class CandidateRecordObjectRepository extends HibernateRecordObjectRepository<CandidateInfo> {

    /** {@inheritDoc} */
    public CandidateRecordObjectRepository(final Class<CandidateInfo> entityClass) {
        super(entityClass);
    }

    @SuppressWarnings("unchecked")
    public Collection<CandidateInfo> searchBySkills(final Collection<PersonSkill> skillList) {

        String query = "";
        if (!skillList.isEmpty()) {
            query = "select c from CandidateInfo c, Person p, PersonSkill ps where c.person = p.id and p.id = ps.person";
        } else {
            query = "select c from CandidateInfo c";
        }
        String subQuery = "select p.id from Person p, PersonSkill ps where p.id = ps.person and ps.skill = ";
        boolean flag = true;
        if (skillList.size() != 0) {
            for (PersonSkill idSkills : skillList) {
                if (flag) {
                    query = query + " and ps.skill = " + idSkills.getSkill().getId();
                    if (idSkills.getLevel() != null && idSkills.getLevel().getId() != null) {
                        query += " and ps.level = " + idSkills.getLevel().getId();
                    }
                    flag = false;
                } else {
                    query = query + " and p.id in ( " + subQuery + idSkills.getSkill().getId();
                    if (idSkills.getLevel() != null && idSkills.getLevel().getId() != null) {
                        query += " and ps.level = " + idSkills.getLevel().getId();
                    }
                    query += " )";
                }

            }
        }

        Query queryCandidate = getSession().createQuery(query);
        return queryCandidate.list();
    }

}
